<template>
  <div class="content">
    <pageHeaderNew title="公共文档" :breadCrumb="breadCrumb"></pageHeaderNew>

    <div class="search-box">
      <div>
        <a-space>
          <a-input-search
            :style="{ width: '420px' }"
            placeholder="搜索"
            style="margin-bottom: 8px; max-width: 240px"
            v-model="searchKey"
          />
        </a-space>
      </div>

      <div>
        <a-space>
          <a-button type="primary" @click="openFolderModal">
            <template #icon>
              <icon-plus />
            </template>
            <template #default>新增文件夹</template>
          </a-button>
          <a-button status="success" @click="openUploadModal">
            <template #icon>
              <icon-plus />
            </template>
            <template #default>上传</template>
          </a-button>
        </a-space>
      </div>
    </div>
    <div class="table-box">
      <a-table
        :pagination="false"
        :data="getTreeData"
        v-model:expandedKeys="expandedKeys"
        show-empty-tree
        style="margin-top: 20px"
        rowKey="id"
      >
        <template #columns>
          <a-table-column :width="200" dataIndex="storeName" title="序号">
            <template #cell="{ record }">
              <icon-font
                :type="
                  !record.downloadPath ? 'icon-wenjianjia' : 'icon-wenjian'
                "
                :size="20"
                style="cursor: pointer; margin-left: 10px"
              />
            </template>
          </a-table-column>
          <a-table-column :width="200" dataIndex="storeName" title="名称">
            <template #cell="{ record }">
              <a-input
                v-if="isShow && record.id === setFileData.id"
                :style="{ width: '320px' }"
                placeholder="Disabled status"
                v-model="setFileName"
                :error="isError"
                @change="changeFileName"
              />
              <div
                v-else
                style="
                  white-space: nowrap;
                  text-overflow: ellipsis;
                  overflow: hidden;
                "
              >
                {{ record.storeName.split('.')[0] }}
              </div></template
            >
          </a-table-column>

          <a-table-column :width="200" title="文件类型">
            <template #cell="{ record }">
              {{
                record.fileName
                  ? `.${record.storeName.split('.')[1]}`
                  : '文件夹'
              }}</template
            >
          </a-table-column>

          <a-table-column :width="200" title="类型">
            <template #cell="{ record }">
              {{ record.fileName ? '文件' : '文件夹' }}</template
            >
          </a-table-column>

          <a-table-column :width="200" title="操作	">
            <template #cell="{ record }">
              <a-space v-if="record.fileName">
                <a-tooltip content="分享">
                  <icon-font
                    type="icon-fenxiangfangshi"
                    :size="19"
                    :style="{
                      marginRight: '10px',
                      cursor: 'pointer'
                    }"
                    @click="goShare(record)"
                  />
                </a-tooltip>
                <a-tooltip content="删除文件">
                  <a-popconfirm
                    content="确定要删除该文件?"
                    type="error"
                    @ok="delFile(record)"
                  >
                    <IconFont
                      type="icon-delete"
                      :size="26"
                      :style="{
                        marginRight: '10px',
                        cursor: 'pointer'
                      }"
                    />
                  </a-popconfirm>
                </a-tooltip>
                <a-tooltip content="更多操作">
                  <a-dropdown>
                    <icon-font
                      type="icon-more-def"
                      :size="26"
                      :style="{
                        cursor: 'pointer'
                      }"
                    />
                    <template #content>
                      <a-doption @click="openTabs(record)"
                        ><template #icon>
                          <icon-font
                            type="icon-xinbiaoqianyedakai"
                            :size="15"
                            :style="{
                              cursor: 'pointer'
                            }"
                          /> </template
                        >新标签页打开</a-doption
                      >
                      <a-doption @click="copy(record)">
                        <template #icon>
                          <icon-font
                            type="icon-lianjie"
                            :size="18"
                            :style="{
                              cursor: 'pointer'
                            }"
                          /> </template
                        >复制链接</a-doption
                      >
                      <a-doption @click="goRename(record)"
                        ><template #icon>
                          <icon-font
                            type="icon-zhongmingming"
                            :size="16"
                            :style="{
                              cursor: 'pointer'
                            }"
                          /> </template
                        >重命名</a-doption
                      >
                      <a-doption @click="setPreview(record)">预览</a-doption>
                      <a-doption @click="SetupCollect(record)"
                        ><template #icon>
                          <icon-font
                            type="icon-shoucang"
                            :size="18"
                            :style="{
                              cursor: 'pointer'
                            }"
                          /> </template
                        >收藏</a-doption
                      >
                      <a-doption @click="SetupSharing(record)"
                        ><template #icon>
                          <icon-font
                            type="icon-gongxiang"
                            :size="18"
                            :style="{
                              cursor: 'pointer'
                            }"
                          /> </template
                        >{{
                          record.shareState === 1 ? '发起共享' : '取消共享'
                        }}</a-doption
                      >
                    </template>
                  </a-dropdown>
                </a-tooltip>
              </a-space>
              <div v-else type="text" @click="setDocument(record)">
                {{ '--' }}
              </div>
            </template>
          </a-table-column></template
        >
      </a-table>
    </div>
  </div>

  <UploadModal ref="uploadRef" @hide="setHide"></UploadModal>
  <FolderModal
    v-model:visible="modalVisible"
    :data="data"
    @addDocumentEmit="setDocument"
  ></FolderModal>
  <FilePreview
    v-model:visible="PreviewModelVisible"
    ref="previewFileRef"
    v-if="previewFile.fileShow"
    :file="previewFile.fileMessage"
    @downLoadFile="downLoadFile"
  >
  </FilePreview>
  <ShareModel
    v-if="shareModelVisible"
    v-model:visible="shareModelVisible"
    :sharingInfo="SharingInfo"
  ></ShareModel>
</template>

<script lang="ts" setup>
import UploadModal from './UploadModal.vue';
import FolderModal from './FolderModal.vue';
import {
  PostStorageDisk,
  getPubliceFileBelong,
  deleteFile,
  putShareState,
  postFileCollect,
  putFileName
} from '@/apis/document/documentCenter/index';
import { Message } from '@arco-design/web-vue';
import useClipboard from 'vue-clipboard3';
import ShareModel from '../components/share.vue';

const SharingInfo = ref({});
const shareModelVisible = ref(false);
const goShare = (res: any) => {
  shareModelVisible.value = true;
  SharingInfo.value = res;
};

const { toClipboard } = useClipboard();
const router = useRouter();
const copy = async (res) => {
  try {
    await toClipboard(res.downloadPath);
    Message.success('复制成功');
  } catch (err: unknown) {
    console.log(err);
  }
};
const setFileName = ref();
const isShow = ref(false);
const fileType = ref();
const setFileData = ref();
const isError = ref(false);
const goRename = async (res: any) => {
  setFileName.value = res.storeName.split('.')[0];
  fileType.value = res.storeName.split('.')[1];
  setFileData.value = res;
  isShow.value = true;
  console.log(setFileData.value, fileType.value, setFileName.value);
};

const changeFileName = async (e: string) => {
  try {
    if (setFileName.value === '') {
      isError.value = true;
      return;
    }
    await putFileName({
      useFileName: `${setFileName.value}.${fileType.value}`,
      id: setFileData.value.id
    });
    getTableData();
    setFileName.value = undefined;
    fileType.value = undefined;
    setFileData.value = undefined;
    isShow.value = false;
    isError.value = false;
  } catch (err: unknown) {
    console.log(err);
  }
};
const openTabs = (res) => {
  router.push({ name: 'FileTabsPage', query: { url: res.downloadPath } });
};
const data = ref({});
const userInfo = JSON.parse(localStorage.getItem('userInfo') as any);
const previewFile = reactive({
  fileShow: false,
  fileMessage: {
    id: '',
    fileName: '',
    downloadUrl: ''
  }
});
const expandedKeys = ref([]);
const PreviewModelVisible = ref(false);
const modalVisible = ref(false);
const getListType = ref(null);
const uploadRef = ref();
const FolderRef = ref();
const searchKey = ref('');
const DocumentsTree = ref([]);
const getTreeData = ref([]);

const setTreeData = (data: any) => {
  data.forEach((item) => {
    if (item.file) {
      item.file.forEach((ele: any) => {
        item.children.push({ ...ele, storeName: ele.useFileName, type: 1 });
      });
    }
    if (item.children) setTreeData(item.children);
  });
  return data;
};

function getMatchIndex(title) {
  if (!searchKey.value) return -1;
  return title.toLowerCase().indexOf(searchKey.value.toLowerCase());
}

const openUploadModal = () => {
  uploadRef.value.visible = true;
};

const openFolderModal = () => {
  modalVisible.value = true;
};

const setPreview = (val: any) => {
  previewFile.fileMessage.id = val.id;
  previewFile.fileMessage.fileName = val.fileName;
  previewFile.fileMessage.downloadUrl = val.downloadPath;
  previewFile.fileShow = true;
  PreviewModelVisible.value = true;
};

const getTableData = async () => {
  try {
    const res = await getPubliceFileBelong();
    getTreeData.value = [res];
    setTreeData(getTreeData.value);
  } catch (err: unknown) {
    console.log(err);
  }
};
getTableData();
const setDocument = async (val: any) => {
  try {
    if (!val.id) await PostStorageDisk({ ...val });
    getTableData();
  } catch (err: unknown) {
    console.log(err);
  }
};

const setHide = (res: boolean) => {
  if (res) getTableData();
};

const SetupSharing = async (val: any) => {
  try {
    await putShareState({ id: val.id });
    getTableData();
  } catch (err: unknown) {
    console.log(err);
  }
};

const delFile = async (res: any) => {
  try {
    await deleteFile({ id: res.id, type: 0 });
    getTableData();
  } catch (err: unknown) {
    console.log(err);
  }
};

const SetupCollect = async (record: any) => {
  try {
    await postFileCollect({ userId: userInfo.id, fileId: record.id });
    getTableData();
  } catch (err: unknown) {
    console.log(err);
  }
};
</script>

<style scoped lang="less">
.content {
  padding: 10px;
  height: 100%;
  width: 100%;
}

.search-box {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  width: 96%;
  margin: 10px;
}

:deep(.arco-table-tr) {
  height: 40px;
}
:deep(.arco-table-th) {
  font-weight: bold;
  // font-size: 13px;
}
</style>
